from django.shortcuts import render,HttpResponse,redirect,reverse
from cmdb.models import hostInfo
from users.models import userInfo,userGroup
from users.views import auth_user
from .models import projectInfo,onlineDetail
import os,json
import datetime
import subprocess
# Create your views here.
@auth_user
def projectIndex(request):
    allhosts = hostInfo.objects.all()
    allusers = userInfo.objects.all()
    allusergroups = userGroup.objects.all()
    allProjects = projectInfo.objects.all()
    return render(request,'deploy-project.html',{
        'allhosts':allhosts,
        'allusers':allusers,
        'allusergroups':allusergroups,
        'allProjects':allProjects,
    })
@auth_user
def addProject(request):
    projectname = request.POST.get('projectname',None)
    hostid = request.POST.get('hostid',None)
    userandgroup = request.POST.getlist('userandgroup[]',None)
    projectdir = request.POST.get('projectdir',None)
    hostid = int(hostid)
    user_obj = []
    usergroup_obj = []
    for i in range(len(userandgroup)):
        if userandgroup[i].startswith('u'):
            uid = int(userandgroup[i].lstrip('u'))
            userobj = userInfo.objects.get(uid=uid)
            user_obj.append(userobj)
        elif userandgroup[i].startswith('g'):
            gid = int(userandgroup[i].lstrip('g'))
            usergroupobj = userGroup.objects.get(gid=gid)
            usergroup_obj.append(usergroupobj)
    projectObj = projectInfo.objects.create(projectName=projectname,projectDir = projectdir,projecthost_id = hostid)
    if len(usergroup_obj) !=0:
        projectObj.projectgrouper.add(*usergroup_obj)
    if len(user_obj) !=0:
        projectObj.projectowner.add(*user_obj)
    projectObj.save()
    return HttpResponse('ok')
@auth_user
def createProject(request):
    baseProjectDir = '/data/workspace/webste/'
    projectname = request.POST.get('projectname',None)
    hostid = request.POST.get('hostid',None)
    userandgroup = request.POST.getlist('userandgroup[]',None)
    projectdir = baseProjectDir + projectname
    return HttpResponse('ok')
@auth_user
def editProject(request):
    projectid = request.POST.get('projectid',None)
    projectname = request.POST.get('projectname',None)
    hostid = request.POST.get('hostid',None)
    userandgroup = request.POST.getlist('userandgroup[]',None)
    projectdir = request.POST.get('projectdir',None)
    projectid=int(projectid)
    hostid = int(hostid)
    user_obj = []
    usergroup_obj = []
    for i in range(len(userandgroup)):
        if userandgroup[i].startswith('u'):
            uid = int(userandgroup[i].lstrip('u'))
            userobj = userInfo.objects.get(uid=uid)
            user_obj.append(userobj)
        elif userandgroup[i].startswith('g'):
            gid = int(userandgroup[i].lstrip('g'))
            usergroupobj = userGroup.objects.get(gid=gid)
            usergroup_obj.append(usergroupobj)
    print(projectid)
    projectObj = projectInfo.objects.get(id = projectid)
    if len(usergroup_obj) !=0:
        projectObj.projectgrouper.clear()
        projectObj.projectgrouper.add(*usergroup_obj)
    else:
        projectObj.projectgrouper.clear()
    if len(user_obj) !=0:
        projectObj.projectowner.clear()
        projectObj.projectowner.add(*user_obj)
    else:
        projectObj.projectowner.clear()
    projectObj.projectName = projectname
    projectObj.projectDir = projectdir
    projectObj.projecthost_id = hostid
    projectObj.save()
    return HttpResponse('ok')
@auth_user
def delProject(request):
    proid = request.POST.get('projectid',None)
    if proid !='':
        proid = int(proid)
        projectInfo.objects.get(id=proid).delete()
        return HttpResponse('ok')


@auth_user
def onlineIndex(request):
    uid = request.session['user_id']
    userObj = userInfo.objects.get(uid=uid)
    allProjects = userObj.projectinfo_set.all()
    return render(request,'deploy-online.html',{'allProjects':allProjects})

@auth_user
# 代码上传
def online_upload(request):
    base_dir = os.path.dirname(os.path.abspath(__file__))
    upload_dir = os.path.join(base_dir,'upload')
    fileobj = request.FILES.get('codefile',None)
    onlineHost = request.POST.get('onlineHostIP')
    onlineownerid = request.POST.get('onlineownerid')
    onlineproid = request.POST.get('onlineproid')
    nowTime = datetime.datetime.now().strftime('%Y%m%d%H%M')
    # 将上传的代码包重命名
    # fileName = nowTime+'.zip' if fileobj.name.endswith('.zip') else nowTime+'.tar.gz'
    filedir = os.path.join(upload_dir,fileobj.name)
    f = open(filedir,mode='wb')
    for i in fileobj.chunks():
        f.write(i)
    f.close()
    # 解压后删除上传的源文件
    codedir = os.path.join(upload_dir,nowTime)
    os.mkdir(codedir)
    os.system('unzip -j %s -d %s'%(filedir,codedir) )
    os.system('rm -fr %s' % filedir)


    #online code
    status = online_code(onlineHost,codedir)
    # record online detail
    onlineDetailObj = onlineDetail()
    onlineDetailObj.onlineCode=nowTime
    onlineDetailObj.onlineOwner_id = int(onlineownerid)
    onlineDetailObj.onlineproject_id = int(onlineproid)
    onlineDetailObj.onlineStatus = status
    onlineDetailObj.save()
    return HttpResponse('ok')

def online_code(onlinehost,sourcecode):
    base_dir = os.path.dirname(os.path.abspath(__file__))
    fab_file = os.path.join(base_dir,'utils','updateCode.py')
    host,port = onlinehost.split(':')
    hostobj = hostInfo.objects.get(hostPublicIP=host,hostSSHPort=port)
    hostuser = hostobj.manageruser.managerName
    hostpwd = hostobj.manageruser.managerPasswd
    print(" fab -u %s -p %s -f %s -H %s go:%s "%(hostuser,hostpwd,fab_file,onlinehost,sourcecode))
    p = subprocess.Popen(" fab -u %s -p %s -f %s -H %s go:%s "%(hostuser,hostpwd,fab_file,onlinehost,sourcecode),shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    p.wait()
    print(p.communicate()[0].decode(encoding='utf-8'))
    returncode = p.returncode
    return returncode

@auth_user
def get_online_detail(request):
    proid = request.POST.get('proid',None)
    prownerid = request.POST.get('prownerid',None)
    detailObj =onlineDetail.objects.filter(onlineOwner_id=int(prownerid),onlineproject_id=int(proid))
    detaillist=[]
    if detailObj.count()>0:
        for d in detailObj:
            eighthours = datetime.timedelta(hours=8)
            bjtime = d.ctime.replace(tzinfo=None)+eighthours
            ctime = bjtime.strftime('%Y-%m-%d %H:%M:%S')
            status = '已上线'if d.onlineStatus==0 else '未上线'
            detaillist.append([d.onlineCode,status,ctime])
    return HttpResponse(json.dumps(detaillist))


@auth_user
def rollback(request):
    pass